<?php
/**
 * Description:
 *
 * @author      Eden
 * @datetime    2017/2/15 09:45
 * @copyright   WuHan HuQi Technology Co.,Ltd.
 * @url         http://cnhuqi.com
 */

class Vdata extends CI_Controller
{

    const USER_ID_START = 1;
    const USER_ID_END = 6263;

    const ORDER_ID_START = 1;
    const ORDER_ID_END = 622;

    const MAX_TIMES_PRE_MINITS = 2;

    private $userid = 0;
    private $addressId = 0;

    /**
     * 数据
     */
    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {

        // 1 点到 8 点不增加
        if (date('G') < 7 && date('G') > 1) {
            return false;
        }

        $times = rand(0, self::MAX_TIMES_PRE_MINITS);
        if (!empty($times)) for ($i = 0; $i < $times; $i++) {
            // 用户数据
            $this->_addUser();

            // 订单
            $addOrder = rand(0, 1);
            $addOrder && $this->_addOrder();
        }

        // 评论
        $this->_addBbs();
        $this->_addPv();
        $this->_addInstallTimes();
        $this->_addStartUpTimes();
    }

    private function _addInstallTimes()
    {
        if (rand(0, 1)) {
            return false;
        }

        $times = rand(1, 3);
        $ios = rand(1, $times);
        $android = $times - $ios;

        statIncr([
            'vInstallTimes' => $times,
            'vIosInstallTimes' => $ios,
            'vAndroidInstallTimes' => $android
        ]);
    }

    private function _addStartUpTimes()
    {
        if (rand(0, 1)) {
            return false;
        }
        $times = rand(1, 15);
        statIncr('vStartUpTimes', $times);
    }

    private function _addPv()
    {
        if (rand(0, 1)) {
            return false;
        }

        $times = rand(2, 30);
        statIncr('vPv', $times);
    }

    private function _addBbs()
    {
        if (rand(0, 1)) {
            $num = rand(1, 3);
            statIncr('vBbsIncr', $num);
        }

    }

    private function _addOrder()
    {

        // goods
        $goodsDb = clone($this->db);
        $counts1 = $goodsDb->count_all('base_goods');
        $counts2 = rand(1, 2);

        $goodsDb->limit($counts2);
        $query = $goodsDb->get_where('base_goods', ['id >=' => rand(0, $counts1)]);
        $goods = $query->result_array();
        $insertOrderGoods = [];
        if (empty($goods)) {
            return false;
        }

        $paymodes = ['online', 'delivery'];
        $payways = [1, 2];
        $status = ['Unpaid','Pending','Dispatch','Complete','Cancel','Refund','Refunded'];

        $paymode = $paymodes[rand(0, 1)];
        $payway = $payways[rand(0, 1)];
        $key = rand(0, 4);
        $s = $status[$key];

        // user_order
        $db = clone($this->db);
        $db->insert('user_order', [
            'sn' => sn(),
            'userId' => $this->userid,
            'totalPrice' => 0,
            'goodsPrice' => 0,
            'expressPrice' => 0,
            'addressId' => 0,
            'payMode' => $paymode, // 'delivery'
            'payWay' => $paymode == 'online' ? $payway : 0, // 1 ali, 2 wechat
            'payStatus' => $key > 1 ? 6 : 0, // 6 完成 3退款 0 未支付
            'message' => '',
            'status' => $s,     //
            'virtual' => 1
        ]);

        $orderid = $db->insert_id();

        $totalPrice = 0;
        if (!empty($goods)) foreach ($goods as $g) {
            $num = rand(1, 2);
            $totalPrice += $g['price'] * $num;
            $insertOrderGoods[] = [
                'orderId' => $orderid,
                'goodsId' => $g['id'],
                'num' => $num,
                'price' => $g['price']
            ];
        }
        $orderGoodsDb = clone($this->db);
        $orderGoodsDb->insert_batch('user_order_goods', $insertOrderGoods);

        $data = [
            'totalPrice' => $totalPrice,
            'goodsPrice' => $totalPrice,
            'addressId' => $this->addressId,
        ];

        if ($key > 2) {
            $data['compTime'] = dateTime();
        }

        $db->where('id', $orderid);
        $db->update('user_order', $data);

        $orderField = ['vAppOrders', 'vWxOrders'];
        statIncr($orderField[rand(0, 1)]);
    }

    private function _addUser()
    {
        $userTypes = ['wx', 'ios', 'android'];
        $key = rand(0, 2);
        $type = $userTypes[$key];
        $db = clone($this->db);
        $query = $db->get_where('v_user', ['id' => rand(self::USER_ID_START, self::USER_ID_END)]);
        $user = $query->row_array();
        unset($db);

        $db = clone($this->db);
        $query = $db->get_where('v_order', ['id' => rand(self::ORDER_ID_START, self::ORDER_ID_END)]);
        $order = $query->row_array();
        unset($db);

        $willAddMoney = rand(1, 20);

        $time = time() + rand(-300, 300);
        $password = encryptPassword(uniqid());
        $userData = [
            'phone' => $order['phone'],
            'password' => $password['password'],
            'salt' => $password['salt'],
            'nickName' => $user['nickname'],
            'lastIp' => $user['last_loginip'],
            'created' => date('Y-m-d H:i:s', $time),
            'source' => $type,
            'score' => rand(0, 100),
            'amount' => $willAddMoney == 1 ? rand(100, 10000) : 0,
            'virtual' => 1
        ];

        $userDb = clone($this->db);
        $userDb->insert('user', $userData);
        $userid = $userDb->insert_id();
        unset($userDb);
        if (empty($userid)) {
            return false;
        }

        $this->userid = $userid;
        $userProfileDb = clone($this->db);
        $userProfileDb->insert('user_profile', [
            'userId' => $userid,
            'avatar' => $user['headimgurl'],
            'bill' => '',
            'trueName' => $order['member_name']
        ]);
        unset($userProfileDb);

        $addrdb = clone($this->db);
        $addrdb->insert('user_address', [
            'userId' => $userid,
            'name' => $order['member_name'],
            'phone' => $order['phone'],
            'address' => $order['address'],
            'default' => 1
        ]);

        $this->addressId = $addrdb->insert_id();

        if ($type == 'wx') {
            $wxDb = clone($this->db);
            $wxData = $user;
            unset($wxData['id'], $wxData['admin'], $wxData['wechatid'], $wxData['name'], $wxData['job'],
                $wxData['mobile'], $wxData['phone'], $wxData['birthday'], $wxData['last_loginip'], $wxData['last_logintime'],
                $wxData['area'], $wxData['address']);
            $wxDb->insert('user_wx', $wxData);
        }

        // daily
        $field = $type == 'wx' ? 'vWxUsers' : 'vAppUsers';
        statIncr($field);
    }
}